package cn.bulgat.spring.web.filter;

import cn.bulgat.common.id.IIdGenerator;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

import static cn.bulgat.spring.web.constant.HttpConstant.LOG_ID_HEADER;

public class LogIdFilter implements Filter {

    private final IIdGenerator<?> idGenerator;

    public LogIdFilter(IIdGenerator<?> idGenerator) {
        this.idGenerator = idGenerator;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
        throws IOException, ServletException {
        try {
            Serializable logId = (Serializable) idGenerator.nextId();
            String logIdStr = String.valueOf(logId);
            MDC.put("reqLogId", logIdStr);  // 将 logId 存入 MDC
            // 将 logId 添加到响应头
            if (response instanceof HttpServletResponse) {
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                if (!httpResponse.isCommitted()) { // 确保响应未提交
                    httpResponse.setHeader(LOG_ID_HEADER, logIdStr);
                }
            }
            chain.doFilter(request, response);
        } finally {
            MDC.clear();  // 请求完成后清除 MDC
        }
    }
}